<template>
	<view class="flex items-center" :class="{ 'justify-center': imageList.length === 1 }">
		<template v-for="(img, index) in imageList" :key="img">
			<image
				mode="aspectFit"
				class="cursor-pointer"
				:class="{ 'ml-8px': index > 0 }"
				v-if="isImage(img)"
				:src="img"
				:style="imageStyle"
				@click="(showImageViewer = true), (initialIndex = index)"
			></image>
			<dx-icon v-else :name="isVideo(img) ? 'video' : isAudio(img) ? 'audio-file' : 'file-addition-one'" size="30"></dx-icon>
		</template>
	</view>
	<!-- 预览 -->
	<el-image-viewer
		v-if="showImageViewer"
		:hide-on-click-modal="hideOnClickModal"
		:initial-index="initialIndex"
		:url-list="imageList"
		@close="showImageViewer = false"
	></el-image-viewer>
</template>
<script setup lang="ts" name="DxImage">
import { computed, ref, watch } from 'vue';
const imageList = ref<any[]>([]);
const showImageViewer = ref(false);
const initialIndex = ref(0);
const isImage = computed(() => {
	return (url: string) => {
		return /\.(jpeg|jpg|gif|png|svg|webp|jfif|bmp|dpg)/i.test(url);
	};
});
const isVideo = computed(()=>{
	return (url: string) => {
		return /\.(mp4|avi|ogg|wmv|mpg|mpeg|mov)/i.test(url);
	};
});
const isAudio = computed(()=>{
	return (url: string) => {
		return /\.(mp3|wav|wma|cda|ape)/i.test(url);
	};
})
const props = withDefaults(
	defineProps<{
		list: string | string[];
		width?: string | number;
		height?: string | number;
		hideOnClickModal?: boolean;
	}>(),
	{
		hideOnClickModal: true,
		width: '45px',
		height: '45px',
	}
);
watch(
	() => props.list,
	(val) => {
		if (typeof val === 'string') {
			imageList.value = [val];
		} else if (Array.isArray(val)) {
			imageList.value = val;
		} else {
			imageList.value = [];
		}
	},
	{ immediate: true }
);
const imageStyle = computed(() => {
	return {
		width: typeof props.width === 'string' ? props.width : props.width + 'px',
		height: typeof props.height === 'string' ? props.height : props.height + 'px',
	};
});
</script>
<style scoped>
image {
	background-color: #f4f6f8;
	border: 1px solid #ebeef5;
}
</style>
